<template>
	<view class="">
		<!-- <view class=""  style='width:0px;height:0px;overflow:hidden;'> -->
			<!-- <scroll-view style="height: 96px;" class="canvas-container" scroll-x="true" bindscroll="handleScroll"> -->
			   <!-- <canvas
			     canvas-id="myCanvas" 
			     :style="{width: canvasWidth+'px', height: canvasHeight + 'px'}"
			   ></canvas> -->
			<!-- </scroll-view> -->

		  
		<!-- </view> -->
		<view class="progress-box" :style="{height: blockSize + 'rpx'}" @tap="handleTapFn">
			<scroll-view class="canvas-container" scroll-x="true" bindscroll="handleScroll">
			<view style="width: 2250rpx;" class="readers-slider" :style="{height: lineSize + 'px',backgroundImage: 'url(' + showImgTemp + ')'}">
				<view
					class="readers-slider__value"
					:style="{
						width: posVal + '%',
						backgroundColor: activeColor,
						borderRadius: '12rpx'
					}"
				>
					<view
						class="rid-box section_4"
						
						@touchstart="touchS"
						@touchmove="touchM"
						@touchend="touchE"
					>
						<view
							:style="{
								
								backgroundColor: blockColor
							}"
							class="dist"
							style="display: flex;justify-content: center;align-items: center;"
						>
							<view
								:style="{
									width: blockSize/4 + 'rpx',
									height: blockSize/4 + 'rpx',
									backgroundColor: activeColor,
									borderRadius: '50%'
								}"
								
							></view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		</view>
		<!-- <view class="container">
		  <view class="slider-container">
		    <image 
		      class="slider-bg" 
		      :style="{ transform: `translateX(${offsetX}px)` }"
		      :src="imageSrc"
		      @load="onImageLoad"
		    />
		    <view class="slider-track">
		      <slider 
		        class="slider"
		        :value="sliderValue" 
		        :block-size="28"
		        :activeColor="activeColor"
		        :backgroundColor="backgroundColor"
		        :block-color="blockColor"
		        @change="onSliderChange"
		      />
		    </view>
		  </view>
		</view> -->
	</view>
  
</template>

<script>
	let sdilderPos = {};
	let sliderWidth = 0;
	let sliderLeft = 0;
	let dragVal = 0;
export default {
	name: 'dc-slider',
	// props: {
	// 	value: {
	// 		default: 0,
	// 		type: Number
	// 	},
	// 	disabled: {
	// 		type: Boolean,
	// 		default: false
	// 	},
	// 	activeColor: {
	// 		type: String,
	// 		default: '#00E3AB'
	// 	},
	// 	min: {
	// 		default: 0,
	// 		type: Number
	// 	},
	// 	max: {
	// 		default: 100,
	// 		type: Number
	// 	},
	// 	step: {
	// 		default: 1,
	// 		type: Number
	// 	},
	// 	lineSize: {
	// 		type: Number,
	// 		default: 4
	// 	},
	// 	blockSize: {
	// 		type: Number,
	// 		default: 32
	// 	},
	// 	//内块颜色
	// 	blockColor: {
	// 		type: String,
	// 		default: '#00e3ab'
	// 	},
	// 	//外圈颜色
	// 	blockOuterColor:{
	// 		type: String,
	// 		default: 'rgba(0, 227, 171, 0.2)'
	// 	}
	// },
	watch: {
		value: {
			//监听进度值变化
			handler(val) {
				if (this.moveLock) {
					return false;
				}
				let _v = val > this.min ? val : this.min;
				this.posVal = (((_v - this.min) * 100) / (this.max - this.min)) > 100 ? 100 : ((_v - this.min) * 100) / (this.max - this.min);
			},
			immediate: true
		}
	},
	
	computed: {
		// #ifdef APP-PLUS-NVUE
		widthPx() {
			let _width = (this.sliderWidth * this.posVal) / 100;
			if (_width > this.sliderWidth) {
				_width = this.sliderWidth;
			}
			return _width;
		},
		//#endif
	},
  data() {
    return {
      // sliderValue: 0,
      // offsetX: 0,
      // intervalId: null,
      // imageWidth: 0,
      // imageSrc: 'https://terminator.axu9.com/images/edit/video-poster.png', // 替换为你的图片路径
      
      // // 颜色配置
      // activeColor: '#FF0000',
      // backgroundColor: '#CCCCCC',
      // blockColor: '#FFFFFF',
	  posVal: 0, //进度条值
	  defVal: 0,
	  moveLock: false ,//操作锁，双向绑定音频进度拖动操作可用（ps可以自己监听更改重置）
	  sliderWidth:0,
	  value: 20,
	  disabled: false,
	  activeColor:'rgba(0,0,0,0)',
	  min: 0,
	  max: 100,
	  step: 1,
	  lineSize: 48,
	  blockSize: 82,
	  //内块颜色
	  blockColor: '#00e3ab',
	  //外圈颜色
	  blockOuterColor:'rgba(0, 227, 171, 0.2)',
	  
	  imgList: [
	        'https://terminator.axu9.com/images/edit/video-poster.png',
	        'https://terminator.axu9.com/images/edit/video-poster.png',
	        'https://terminator.axu9.com/images/edit/video-poster.png',
	        'https://terminator.axu9.com/images/edit/video-poster.png',
	        'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png',
			'https://terminator.axu9.com/images/edit/video-poster.png'
	      ],
	      canvasWidth: 0,
	      canvasHeight: 0,
		  showImgTemp: 'https://terminator.axu9.com/frames/45100123224.jpg'
    };
  },
  // mounted() {
    // 初始化时尝试启动（等待图片加载）
    // this.startAutoMove();
  // },
  onLoad() {
      // this.loadImages();
	  
    },
  mounted() {
  	console.log(this.blockColor.indexOf('#'))
  	//#ifndef APP-PLUS-NVUE
  	const query = uni.createSelectorQuery().in(this);
  	query
  		.select('.readers-slider')
  		.boundingClientRect(data => {
  			// console.log(data);
  			sliderWidth = data.width;
  			sliderLeft = data.left;
  		})
  		.exec();
  	//#endif
  	//#ifdef APP-PLUS-NVUE
  	setTimeout(() => {
  		const result = dom.getComponentRect(this.$refs.reaSlider, option => {
  			console.log('PLUS-NVUE:getComponentRect:', option);
  			sliderWidth = option.size.width;
  			sliderLeft = option.size.left;
  			this.sliderWidth = option.size.width
  		});
  	}, 300);
  	//#endif
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.intervalId);
  },
  methods: {
	  // 加载所有图片
	    async loadImages() {
	      const imgList = this.imgList;
	      const imgInfoList = [];
	   
	      // 并行加载图片信息
	      const promises = imgList.map(img => 
	        new Promise((resolve, reject) => {
	          wx.getImageInfo({
	            src: img,
	            success: res => resolve(res),
	            fail: reject
	          });
	        })
	      );
	   
	      try {
	        const results = await Promise.all(promises);
	        imgInfoList.push(...results);
	        console.log(imgInfoList,'imgInfoList')
	        // 计算画布尺寸
	        const height = imgInfoList[0].height;
	        let width = 0;
	        imgInfoList.forEach(info => width += info.width);
			// this.canvasWidth = width;
			// this.canvasHeight = height;
			const systemInfo = wx.getSystemInfoSync();
			console.log(systemInfo.screenWidth, 'systemInfo')
			// this.canvasWidth = systemInfo.screenWidth;
			this.canvasWidth = width;
			this.canvasHeight = 48;
			this.drawCanvas(imgInfoList);
	        // this.setData({
	        //   canvasWidth: width,
	        //   canvasHeight: height
	        // }, () => {
	        //   this.drawCanvas(imgInfoList);
	        // });
	      } catch (error) {
	        console.error('图片加载失败:', error);
	      }
	    },
	   
	    // 绘制画布
	    drawCanvas(imgInfoList) {
	      const ctx = wx.createCanvasContext('myCanvas');
	      let x = 0;
	   
	      // imgInfoList.forEach((imgInfo, index) => {
	      //   ctx.drawImage(
	      //     imgInfo.path,
	      //     x, 0,
	      //     imgInfo.width,
	      //     imgInfo.height
	      //   );
	      //   x += imgInfo.width;
	      // });
	    ctx.drawImage(imgInfoList[0].path,0,0,150,48)
		ctx.drawImage(imgInfoList[1].path,150,0,150,48)
		ctx.drawImage(imgInfoList[2].path,150 *2,0,150,48)
		ctx.drawImage(imgInfoList[3].path,150 *3,0,150,48)
		ctx.drawImage(imgInfoList[4].path,150 *4,0,150,48)
		ctx.drawImage(imgInfoList[5].path,150 *5,0,150,48)
		ctx.drawImage(imgInfoList[6].path,150 *6,0,150,48)
		ctx.drawImage(imgInfoList[7].path,150 *7,0,150,48)
		ctx.drawImage(imgInfoList[8].path,150 *8,0,150,48)
		ctx.drawImage(imgInfoList[9].path,150 *9,0,150,48)
		ctx.drawImage(imgInfoList[10].path,150 *10,0,150,48)
		ctx.drawImage(imgInfoList[11].path,150 *11,0,150,48)
		ctx.drawImage(imgInfoList[12].path,150 *12,0,150,48)
		ctx.drawImage(imgInfoList[13].path,150 *13,0,150,48)
		ctx.drawImage(imgInfoList[14].path,150 *14,0,150,48)
		ctx.drawImage(imgInfoList[15].path,150 *15,0,150,48)
		ctx.drawImage(imgInfoList[16].path,150 *16,0,150,48)
		// ctx.drawImage(imgInfoList[3].path,450,0,150,96)
		// ctx.drawImage(imgInfoList[4].path,600,0,150,96)
	      ctx.draw(false, () => {
	        wx.canvasToTempFilePath({
	          canvasId: 'myCanvas',
	          success: res => {
	            // this.saveImage(res.tempFilePath);
				this.showImgTemp = res.tempFilePath
				console.log(this.showImgTemp,'showImgTemp')
	          },
	          fail: err => console.error(err)
	        });
	      });
	    },
	   
	    // 保存图片
	    saveImage(tempFilePath) {
	      wx.saveImageToPhotosAlbum({
	        filePath: tempFilePath,
	        success: () => {
	          wx.showToast({
	            title: '保存成功',
	            icon: 'success'
	          });
	        },
	        fail: err => {
	          console.error('保存失败:', err);
	          if (err.errMsg.includes('auth deny')) {
	            wx.showModal({
	              title: '提示',
	              content: '需要相册权限才能保存图片',
	              showCancel: false
	            });
	          }
	        }
	      });
	    },
	  //点击进度条跳到进度位置
	  handleTapFn(e) {
	  	if (this.disabled) return;
	  	this.moveLock = true;
	  	let page_x = e.detail.x?e.detail.x:e.detail.pageX;
	  	let Pos_v = ((page_x - sliderLeft) / sliderWidth) * 100;
	  	let val = Math.round(Pos_v);
	  	if (val > 100) {
	  		this.defVal = 100;
	  	} else if (val < 0) {
	  		this.defVal = 0;
	  	} else {
	  		let r = (100 / (this.max - this.min)) * this.step;
	  		let v = Math.round(val / r) * r;
	  		this.defVal = v;
	  	}
	  	let d = this.max - this.min;
	  	dragVal = Math.round(((d * this.defVal) / 100 + this.min) * 100) / 100;
	  	this.posVal = Math.round(this.defVal);
	  	this.$emit('changed', { progress: this.posVal, value: dragVal });
	  	setTimeout(() => {
	  		this.moveLock = false;
	  	}, 1000);
	  },
	  handleTapWeex() {//APP-PLUS-NVUE
	  	if (this.disabled) return;
	  	this.moveLock = true;
	  	let m = sdilderPos.touchE;
	  	let page_x = m.pageX;
	  	let Pos_v = ((page_x) / sliderWidth) * 100;
	  	let val = Math.round(Pos_v);
	  	if (val > 100) {
	  		this.defVal = 100;
	  	} else if (val < 0) {
	  		this.defVal = 0;
	  	} else {
	  		let r = (100 / (this.max - this.min)) * this.step;
	  		let v = Math.round(val / r) * r;
	  		this.defVal = v;
	  	}
	  	let d = this.max - this.min;
	  	dragVal = Math.round(((d * this.defVal) / 100 + this.min) * 100) / 100;
	  	this.posVal = Math.round(this.defVal);
	  	this.$emit('changed', { progress: this.posVal, value: dragVal });
	  	setTimeout(() => {
	  		this.moveLock = false;
	  	}, 1000);
	  },
	  touchS(e) {
	  	if (this.disabled) return;
	  	this.moveLock = true;
	  	let s = e.changedTouches[0];
	  	sdilderPos.touchS = s;
	  	sdilderPos.touchS.val = this.posVal;
	  },
	  touchM(e) {
	  	if (this.disabled) return;
	  	let m = e.changedTouches[0];
	  	let Pos_v = Number(sdilderPos.touchS.val) + ((m.pageX - sdilderPos.touchS.pageX) / sliderWidth) * 100;
	  	let val = Math.round(Pos_v);
	  	if (val > 100) {
	  		this.defVal = 100;
	  	} else if (val < 0) {
	  		this.defVal = 0;
	  	} else {
	  		let r = (100 / (this.max - this.min)) * this.step;
	  		let v = Math.round(val / r) * r;
	  		this.defVal = v;
	  	}
	  	var d = this.max - this.min;
	  	dragVal = Math.round(((d * this.defVal) / 100 + this.min) * 100) / 100;
	  	this.posVal = Math.round(this.defVal);
	  	this.$emit('changing', { progress: this.posVal, value: dragVal });
	  },
	  touchE(e) {
	  	if (this.disabled) return;
	  	this.$emit('changed', { progress: this.posVal, value: dragVal });
	  	let s = e.changedTouches[0];
	  	sdilderPos.touchE = s;
	  	setTimeout(() => {
	  		this.moveLock = false;
	  	}, 1000);
	  },
    // // 图片加载完成回调
    // onImageLoad(e) {
    //   this.imageWidth = e.detail.width;
    //   // this.startAutoMove();
    // },
    
    // // 启动自动移动
    // startAutoMove() {
    //   if (!this.imageWidth) return;
      
    //   this.intervalId = setInterval(() => {
    //     // 计算新值（保持0-100范围）
    //     const step = this.imageWidth / 100; // 假设图片宽度对应100个单位
    //     this.sliderValue = (this.sliderValue + step) % 100;
    //     this.offsetX = -this.sliderValue * step;
    //   }, 1000);
    // },
    
    // // 滑块手动改变时停止自动移动
    // onSliderChange(e) {
    //   clearInterval(this.intervalId);
    //   this.sliderValue = e.detail.value;
    // }
  }
};
</script>
<style>
/* #ifdef APP-PLUS-NVUE */
.progress-box {
	height: 32rpx;
	position: relative;
	display: flex;
	align-items: center;
	flex-direction: row;
}
.readers-slider {
	background-color: #d8d8d8;
	border-radius: 2px;
	width: 100%;
	display: flex;
	flex: 1;
	flex-direction: row;
	align-items: center;
	position: relative;
}
.readers-slider__value {
	/* background-color: #00e3ab; */
	height: 100%;
	position: relative;
	font-size: 0;
	align-items: center;
	border-radius: 12rpx;
}
.dist {
	background-color: #00e3ab;
	height: 16rpx;
	width: 16rpx;
	border-radius: 50%;
}
.rid-box {
	background-color: rgba(0, 227, 171, 0.2);
	height: 32rpx;
	width: 32rpx;
	border-radius: 50%;
	position: absolute;
	left: 0;
	top: 0;
	align-items: center;
	justify-content: center;
}
/*  #endif  */
</style>

<style lang="stylus" scoped>
	.section_4 {
		background-color: #f9fafe;
		box-shadow: 0rpx 0rpx 9.2rpx 0.8rpx #060e2e42;
		border-radius: 2.5rpx;
		width: 5rpx;
		height: 160rpx;
	}
/* #ifndef APP-PLUS-NVUE */
.progress-box
	width 100%
	min-width 200rpx
	height 32rpx
	position relative
	display flex
	align-items center
	.readers-slider
		background #D8D8D8
		border-radius 2px
		width 100%
		height 2px
		background-repeat: no-repeat
		background-size: 100% 100%
		.readers-slider__value
			// background #00E3AB
			height 100%
			position relative
			font-size 0
			.dist
				background #00E3AB
				display inline-block
				height 16rpx
				width 16rpx
				border-radius 50%
				position absolute
				right 50%
				top 50%
				transform translate(50%, -50%)
			.rid-box
				// background rgba(0, 227, 171, 0.2)
				// height 32rpx
				// width 32rpx
				// border-radius 50%
				position absolute
				right 0
				top 50%
				transform translate(50%, -50%)
/*  #endif  */
</style>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.slider-container {
  position: relative;
  width: 300px; /* 初始占位宽度，实际由图片决定 */
  height: 60px;
  overflow: hidden;
}

.slider-bg {
  position: absolute;
  height: 60px;
  transition: transform 0.3s ease-in-out;
}

.slider-track {
  position: relative;
  width: 100%;
  height: 100%;
}

.slider {
  width: 100%;
  height: 100%;
}
</style>